import React, { useEffect } from "react";
import * as echarts from "echarts";
import { accountQuery } from "../services/accountService";

export default function Total() {
  useEffect(() => {
    (async () => {
      let res = await accountQuery({}); //查询
      let list = res.data; //找到数据的集合
      console.log(list);
      if (list.length) {
        //判断长度有没有
        let dateList = Array.from(
          new Set(list.map((item) => item.date))
        ).sort(); //时间的集合

        //根据时间 进行分组统计
        //所有的收入的集合
        let list1 = list.filter((item) => item.type == 1);

        let list2 = dateList.map((date) => {
          let total = 0;
          let selectedList = list1.filter((info) => info.date == date);
          //表示这个日期是存在的
          if (selectedList.length) {
            total = selectedList
              .map((item) => item.money * 1)
              .reduce((a, b) => a + b);
          }
          return total;
        });

        //支出的统计
        //所有的收入的集合
        let list3 = list.filter((item) => item.type == 0);

        let list4 = dateList.map((date) => {
          let total = 0;
          let selectedList = list3.filter((info) => info.date == date);
          //表示这个日期是存在的
          if (selectedList.length) {
            total = selectedList
              .map((item) => item.money * 1)
              .reduce((a, b) => a + b);
          }
          return total;
        });

        var chartDom = document.getElementById("main");
        var myChart = echarts.init(chartDom);
        var option;
        option = {
          xAxis: {
            type: "category",
            data: dateList,
          },
          yAxis: {
            type: "value",
          },
          title: {
            text: "收支统计",
          },
          tooltip: {},
          legend: {
            data: ["金额"],
          },
          series: [
            {
              name: "支出",
              data: list4,
              type: "line",
            },
            {
              name: "收入",
              data: list2,
              type: "line",
            },
          ],
        };
        option && myChart.setOption(option);

        window.addEventListener('resize', function() {
          myChart.resize();
        });
      }
    })();
  }, []);
  return (
    <div>
      <div id="main" style={{ height: "600px" }}></div>
    </div>
  );
}
